<template> 
  <div class="app-container">
    <!-- <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="活动名称：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="活动名称" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card> -->
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini"  type="primary" class="btn-add" @click="handleAdd()" style="margin-left: 20px">添加拼团</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="flashTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <!-- <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column> -->
        <el-table-column label="商品图片" align="center" width="100" > 
          <template slot-scope="scope"><img style="height: 50px" :src="scope.row.product.pic"></template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">{{scope.row.product.name}}</template>
        </el-table-column>
        <el-table-column label="商品规格" align="center">
          <template slot-scope="scope">{{scope.row.skuStock.spData | stringToArr}}</template>
        </el-table-column>
        <el-table-column label="拼团价格" align="center">
          <template slot-scope="scope">{{scope.row.groupPrice}}</template>
        </el-table-column>
        <el-table-column label="活动状态" width="140" align="center">
          <template slot-scope="scope">{{scope.row |formatActiveStatus}}</template>
        </el-table-column>
        <el-table-column label="开始时间" width="160" align="center">
          <template slot-scope="scope">{{scope.row.startTime}}</template>
        </el-table-column>
        <el-table-column label="结束时间" width="160" align="center">
          <template slot-scope="scope">{{scope.row.endTime }}</template>
        </el-table-column>

        <el-table-column label="最大人数" width="80" align="center">
          <template slot-scope="scope">{{scope.row.maxNum}}</template>
        </el-table-column>

        <el-table-column label="最少人数" width="80" align="center">
          <template slot-scope="scope">{{scope.row.miniNum}}</template>
        </el-table-column>

      
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text"   @click="handleUpdate(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button size="mini"
                       type="text"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      title="添加拼团"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="formData"
               ref="flashPromotionForm"
               label-width="150px" size="small">

        <el-form-item label="选择商品：">
          <el-input v-model="formData.productName" style="width: 300px" disabled></el-input>
          <el-button @click="handleSelectProduct" type="primary" size="small">选择商品</el-button>
        </el-form-item>
        <el-form-item label="选择规格：" v-if="formData.productName">
          <el-input v-model="skuForm.skuName" style="width: 300px" disabled></el-input>
          <el-button @click="handleShowSkuEditDialog" type="primary" size="small">选择商品规格</el-button>
        </el-form-item>
        <el-form-item label="开始时间：">
          <el-date-picker
            v-model="startTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
          <el-time-select
            v-model="startValue"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '23:30'
            }"
            placeholder="选择时间">
          </el-time-select>
        </el-form-item>
        <el-form-item label="结束时间：">
          <el-date-picker
            v-model="endTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
          <el-time-select
            v-model="endValue"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '23:30'
            }"
            placeholder="选择时间">
          </el-time-select>
        </el-form-item> 
        <el-form-item label="拼团价格：">
          <el-input v-model="formData.groupPrice" type="number" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="最大人数：">
          <el-input v-model="formData.maxNum" type="number" style="width: 200px"></el-input>
        </el-form-item>
        <el-form-item label="最少人数：">
          <el-input v-model="formData.miniNum" type="number" style="width: 200px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="选择商品" :visible.sync="selectDialogVisible" width="50%">
      <el-input v-model="dialogData.listQuery.keyword"
                style="width: 250px;margin-bottom: 20px"
                size="small"
                placeholder="商品名称搜索">
        <el-button slot="append" icon="el-icon-search" @click="handleSelectSearch()"></el-button>
      </el-input>
      <el-table :data="dialogData.list"
      highlight-current-row
                @current-change="handleDialogSelectionChange" border> 
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="货号" width="160" align="center">
          <template slot-scope="scope">NO.{{scope.row.productSn}}</template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">￥{{scope.row.price}}</template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleDialogSizeChange"
          @current-change="handleDialogCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="dialogData.listQuery.pageNum"
          :page-size="dialogData.listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="dialogData.total">
        </el-pagination>
      </div>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button  size="small" @click="selectDialogVisible = false">取 消</el-button>
        <el-button  size="small" type="primary" @click="handleSelectDialogConfirm()">确 定</el-button>
      </div>
    </el-dialog>


     
    <el-dialog
      title="选择货品信息"
      :visible.sync="skuForm.dialogVisible"
      width="40%">
       
      <el-table style="width: 100%;"
                :data="skuForm.stockList"
                highlight-current-row
                @current-change="handleSkuChange"
                border>
        <el-table-column
          label="SKU编号"
          align="center">
          <template slot-scope="scope">
             {{ scope.row.skuCode }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item,index) in skuForm.productAttr"
          :label="item.name"
          :key="item.id"
          align="center">
          <template slot-scope="scope">
            {{getProductSkuSp(scope.row,index)}}
          </template>
        </el-table-column>
        <el-table-column
          label="销售价格"
          width="80"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column
          label="商品库存"
          width="80"
          align="center">
          <template slot-scope="scope">
            {{ scope.row.stock }}
          </template>
        </el-table-column> 
      </el-table>
      <!-- <span slot="footer" class="dialog-footer">
        <el-button @click="skuForm.dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSkuConfirm">确 定</el-button>
      </span> -->
    </el-dialog>


  </div>
</template>
<script>
  import {getList, del, add, update} from '@/api/group';
  import {formatDate} from '@/utils/date';
  import {fetchList as fetchProductList} from '@/api/product';
  import {fetchList as fetchSkuStockList} from '@/api/skuStock'
  import {fetchList as fetchProductAttrList} from '@/api/productAttr'

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 15,
  };
  const defaultData = {
    groupPrice: null,
    productId: null,
    productSkuId: null,
    miniNum: '',
    maxNum: '',
    startTime: '',
    endTime: '',
  };
  export default {
    name: 'flashPromotionList',
    data() {
      return {
        skuForm:{
          dialogVisible:false,
          productId:null,
          skuName: null,
          productSn:'',
          productAttributeCategoryId:null,
          stockList:[],
          productAttr:[],
          keyword:null
        },
        startValue:'',
        endValue:'',
        startTime:'',
        endTime:'',
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        dialogVisible: false,
        formData: Object.assign({}, defaultData),
        isEdit: false,
        editId: null,
        selectDialogVisible:false,
        dialogData:{
          list: null,
          total: null,
          multipleSelection:'',
          listQuery:{
            keyword: null,
            pageNum: 1,
            pageSize: 5
          }
        }
      }
    },
    created() {
      this.getList();
    },
    filters: {
      stringToArr(value) {
        return JSON.parse(value).map(item => item.value).join('_');
      },
      formatActiveStatus(row) {
        return row.groupStatus == 0 ? '未开始' : row.groupStatus == 1 ? '进行中' : row.groupStatus == 2 ? '拼单成功' : '拼单失败'
        
      },
      formatDate(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    methods: {
      getProductSkuSp(row, index) {
        let spData = JSON.parse(row.spData);
        if(spData!=null&&index<spData.length){
          return spData[index].value;
        }else{
          return null;
        }
      },

      handleShowSkuEditDialog(index,row){
        this.skuForm.dialogVisible=true;
        fetchSkuStockList(this.formData.productId).then(response=>{
          this.skuForm.stockList=response.data;
        }); 
        if(this.skuForm.productAttributeCategoryId!=null){
          fetchProductAttrList(this.skuForm.productAttributeCategoryId,{type:0}).then(response=>{
            this.skuForm.productAttr=response.data.list;
          });
        }
      },
      handleEditSkuConfirm(){
        if(this.editSkuInfo.stockList==null||this.editSkuInfo.stockList.length<=0){
          this.$message({
            message: '暂无sku信息',
            type: 'warning',
            duration: 1000
          });
          return
        }
        this.$confirm('是否要进行修改', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          updateSkuStockList(this.editSkuInfo.productId,this.editSkuInfo.stockList).then(response=>{
            this.$message({
              message: '修改成功',
              type: 'success',
              duration: 1000
            });
            this.editSkuInfo.dialogVisible=false;
          });
        });
      },

      handleSkuChange(row){
        this.formData.productSkuId=row.id;
        const arr = JSON.parse(row.spData);
        this.skuForm.skuName = arr.map(item => item.value).join('_');
        this.skuForm.dialogVisible=false;
      },


      handleSelectProduct(){
        this.selectDialogVisible=true;
        this.getDialogList();
      },

      handleSelectSearch(){
        this.getDialogList();
      },
      handleDialogSizeChange(val) {
        this.dialogData.listQuery.pageNum = 1;
        this.dialogData.listQuery.pageSize = val;
        this.getDialogList();
      },
      handleDialogCurrentChange(val) {
        this.dialogData.listQuery.pageNum = val;
        this.getDialogList();
      },
      handleDialogSelectionChange(val){
        this.dialogData.multipleSelection = val;
      },
      handleSelectDialogConfirm(){
        if (this.dialogData.multipleSelection === '') {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        let selectProducts = {};
        selectProducts.productAttributeCategoryId = this.dialogData.multipleSelection.productAttributeCategoryId;
        selectProducts.productId = this.dialogData.multipleSelection.id;
        selectProducts.productSkuId = this.dialogData.multipleSelection.productSn;
        selectProducts.productName = this.dialogData.multipleSelection.name;

        this.$confirm('使用要进行添加操作?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.formData.productId = selectProducts.productId;
            this.skuForm.productAttributeCategoryId = selectProducts.productAttributeCategoryId;
            this.formData.productSkuId = selectProducts.productSkuId;
            this.formData.productName = selectProducts.productName;
            this.selectDialogVisible=false;
            this.dialogData.multipleSelection=''; 
            this.$message({
              type: 'success',
              message: '添加成功!'
            });
        });
      },


      getDialogList(){
        fetchProductList(this.dialogData.listQuery).then(response=>{
          this.dialogData.list=response.data.list;
          this.dialogData.total=response.data.total;
        })
      },


      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.formData = Object.assign({},defaultData);
      },
      handleShowSessionList() {
        this.$router.push({path: '/sms/flashSession'})
      },
      handleStatusChange(index, row) {
        this.$confirm('是否要修改该状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(row.id, {status: row.status}).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        this.$confirm('是否要删除该活动?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteFlash(row.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          });
        });
      },
      stringToArr(value) {
        return JSON.parse(value).map(item => item.value).join('_');
      },
      handleUpdate(index, row) {
        this.dialogVisible = true;
        this.isEdit = true;
        this.editId = row.id;
        for (const key in this.formData) {
            if (row[key] != null && row[key] != undefined) { 
              this.formData[key] = row[key]
            }
        } 
        this.formData.productName = row.product.name;
        this.skuForm.skuName = this.stringToArr(row.skuStock.spData);
        // this.formData = Object.assign({},row);
        this.startTime = this.formData.startTime.split(' ')[0];
        this.startValue = this.formData.startTime.split(' ')[1];
        this.endTime = this.formData.endTime.split(' ')[0];
        this.endValue = this.formData.endTime.split(' ')[1];
      },
      handleDialogConfirm() {
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.isEdit) {
            this.formData.startTime = this.startTime + ' ' + this.startValue+':00';
            this.formData.endTime = this.endTime + ' ' + this.endValue+':00';
            this.formData.id = this.editId
            update(this.formData).then(response => {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          } else {
            this.formData.startTime = this.startTime + ' ' + this.startValue+':00';
            this.formData.endTime = this.endTime + ' ' + this.endValue+':00';
            add(this.formData).then(response => {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          }
        })
      },
      handleSelectSession(index,row){
        this.$router.push({path:'/sms/selectSession',query:{flashPromotionId:row.id}})
      },
      getList() {
        this.listLoading = true;
        getList(this.listQuery).then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        });
      }
    }
  }
</script>
<style></style>


